package com.lagou.cl.server;

import com.lagou.cl.core.*;
import com.lagou.cl.pojo.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class Catalina {


	private StandardServer standardServer;

	private Mapper mapper = new Mapper();

	public Catalina() {
	}

	public void load() {

		this.loadServerConfig();

		if (standardServer != null) {
			this.standardServer.init();
		}
	}

	public void start() {
		if (standardServer != null) {
			this.standardServer.start();
		}
	}

	/**
	 * 加载server.xml
	 */
	private void loadServerConfig() {
		System.out.println("两个moudle,如下：");
		InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
		try {
			Document document = new SAXReader().read(resourceAsStream);

			StandardServer standardServer = new StandardServer();
			Element server = document.getRootElement();
			//找出所有service
			List<StandardService> standardServiceList = new ArrayList<>();
			List<Element> services = server.elements("Service");
			for (Element service : services) {

				//加载connector
				List<Connector> connectorList = new ArrayList<>();
				List<Element> connectors = service.elements("connector");
				for (Element connector : connectors) {
					String port = connector.attributeValue("port");
					Connector connect = new Connector();
					connect.setPort(Integer.valueOf(port));

					connectorList.add(connect);
				}

				StandardEngine standardEngine = new StandardEngine();
				Element engine = service.element("Engine");
				//加载host
				List<StandardHost> standardHosts = new ArrayList<>();
				List<Element> hosts = engine.elements("Host");
				for (Element host : hosts) {
					StandardHost standardHost = new StandardHost();
					String name = host.attributeValue("name");
					String appBase = host.attributeValue("appBase");
					standardHost.setName(name);
					standardHost.setAppBase(appBase);

					//加载context
					List<Element> contexts = host.elements("Context");
					List<StandardContext> standardContexts = new ArrayList<>();
					for (Element context : contexts) {
						StandardContext standardContext = new StandardContext();

						String docBase = context.attributeValue("name");
						String path = context.attributeValue("path");
						standardContext.setDocBase(docBase);
						standardContext.setPath(path);
						standardContexts.add(standardContext);
						//加载web.xml,封装wrapper();
					}
					standardHost.setStandardContexts(standardContexts);

					//
					standardHosts.add(standardHost);
				}
				standardEngine.setStandardHosts(standardHosts);

				standardServiceList.add(new StandardService(standardEngine, connectorList));
			}

			standardServer.setStandardServices(standardServiceList);

			this.standardServer = standardServer;

		} catch (DocumentException e) {
			e.printStackTrace();

		}
	}
}
